﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeatheRx.Data;
using WeatheRx.DomainModel.Search;

namespace WeatheRx.Managers
{
    public interface IContractorManager
    {
        List<ContractorHeaderModel> GetAll(int agencyId, bool includeOld = false);

        List<ContractorHeaderModel> Search(string searchTerm, int agencyId, bool includeOld = false);

        Contractor Get(int contractorId);

        void Store(Contractor contractor);
    }

    public class ContractorManager : IContractorManager
    {
        public List<ContractorHeaderModel> GetAll(int agencyId, bool includeOld = false)
        {
            List<ContractorHeaderModel> result;
            using (var db = new HWAPEntities())
            {
                var contractors = (includeOld)
                    ? db.Contractors.Where(x => x.ContractorId == agencyId).ToList()
                    : db.Contractors.Where(x => x.ContractorId == agencyId && x.Deleted == false).ToList();
                result = Mapper.Map<List<ContractorHeaderModel>>(contractors);
            }
            return result.OrderBy(x => x.ContrCode).ToList();
        }

        public List<ContractorHeaderModel> Search(string searchTerm, int agencyId, bool includeOld = false)
        {
            return GetAll(agencyId, includeOld)
                .Where(x => (x.CompanyName + " " + x.ContrCode + " " + x.ContrID).Contains(searchTerm))
                .OrderBy(x => x.CompanyName.Contains(searchTerm))
                .ToList();
        }

        public Contractor Get(int contractorId)
        {
            Contractor result;
            using (var db = new HWAPEntities())
            {
                result = db.Contractors.First(x => x.ContractorId == contractorId);
            }
            return result;
        }

        public void Store(Contractor contractor)
        {
            if (contractor.ContractorId > 0)
                Update(contractor);
            else
                Add(contractor);
        }

        private void Update(Contractor contractor)
        {
            using (var db = new HWAPEntities())
            {
                var firstOrDefault = db.Contractors.FirstOrDefault(x => x.ContractorId == contractor.ContractorId);
                if (firstOrDefault != null)
                {
                    Mapper.Map(contractor, firstOrDefault);
                }
                else
                {
                    Add(contractor);
                }
            }
        }

        private void Add(Contractor contractor)
        {
            using (var db = new HWAPEntities())
            {
                db.Contractors.Add(contractor);
                db.SaveChanges();
            }
        }
    }
}